<script setup>
import { ref, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
const I18n = useI18n();
const { locale } = useI18n();
import axios from "axios";
const router = useRouter();
// 跳转页面
const jumpTo = (path) => {
  router.push(path);
};

// 状态列表
let options = ref([
  {
    label: "全部订单2222",
    value: 9,
  },
  {
    label: "待付款",
    value: 0,
  },
  {
    label: "待发货",
    value: 1,
  },
  {
    label: "待收货",
    value: 2,
  },
  {
    label: "待评价",
    value: 3,
  },
  {
    label: "已完成",
    value: 4,
  },
  {
    label: "售后",
    value: 5,
  },
]);

const orderList = ref([]);

const getOrderList = async () => {
  let url = `${apiUrl}/order/list?type=${selectedStatus.value}&search=${searchVal.value}&page=1&limit=100`;
  if (selectedStatus.value === 5) {
    url = `${apiUrl}/pc/get_refund_order_list?type=-3&page=1&limit=1000`;
  }
  try {
    const res = await axios.get(url, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      if (selectedStatus.value === 5) {
        orderList.value = res.data.data.list;
      } else {
        orderList.value = res.data.data;
      }
    }
  } catch (e) {}
};

const getOrderStatusName = (order) => {
  if (order.status === 0 && order.paid === 0) {
    return "待付款";
  }
  if (order.status === 0 && order.paid === 1) {
    return "待发货";
  }
  if (order.status === 1) {
    return "待收货";
  }
  if (order.status === 2) {
    return "带评价";
  }
  if (order.status === 3) {
    return "已完成";
  }
};

// 已选中的状态
const selectedStatus = ref(9);

// 查询部分
let searchVal = ref("");

const changeStatus = () => {
  getOrderList();
};

const cancelOrder = async (id) => {
  ElMessageBox.alert("确认取消该订单", "提示", {
    confirmButtonText: "确定",
    callback: async (action) => {
      try {
        const res = await axios.post(
          `${apiUrl}/order/cancel`,
          { id },
          {
            headers: {
              Authorization: `Bearer ${getToken()}`,
            },
          }
        );

        getOrderList();
      } catch (e) {}
    },
  });
};

const confirmOrder = async (order) => {
  try {
    // 使用 Element Plus 的 ElMessageBox 弹出确认框
    await ElMessageBox.confirm("您确定要确认收货吗？", "确认收货", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 如果用户点击了确定按钮，执行确认收货的逻辑
    const res = await axios.post(
      `${apiUrl}/order/take`,
      {
        uni: order.order_id,
      },
      {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      }
    );

    if (res.data.status === 200) {
      ElMessage({
        message: "已确认收货",
        type: "success",
      });
      getOrderList();
    }
  } catch (error) {
    // 如果用户点击了取消按钮，或者请求失败，不执行任何操作
    if (error !== "cancel") {
      console.error("确认收货失败:", error);
    }
  }
};

onMounted(() => {
  getOrderList();
});
</script>

<template>
  <div class="searchBox">
    <el-select
      v-model="selectedStatus"
      placeholder="Select"
      style="width: 240px"
      @change="changeStatus"
    >
      <el-option label="全部订单" :value="9" />
      <el-option label="待付款" :value="0" />
      <el-option label="待发货" :value="1" />
      <el-option label="待收货" :value="2" />
      <el-option label="待评价" :value="3" />
      <el-option label="已完成" :value="4" />
      <el-option label="售后" :value="5" v-if="1 === 2" />
    </el-select>

    <el-input
      v-model="searchVal"
      :placeholder="$t('account.orderPlace')"
      style="width: 240px; margin-left: 15px"
    >
      <template #append>
        <el-button :icon="Search" @click="changeStatus" />
      </template>
    </el-input>
  </div>
  <div class="orderList">
    <div class="item" v-for="(item, index) in orderList" :key="index">
      <div class="topOrderInfo">
        <div class="date">{{ $t("account.date") }}{{ item._add_time }}</div>
        <div class="orderId" @click="jumpTo('/myorder?id=' + item.order_id)">
          {{ $t("account.orderId") }}{{ item.order_id }}
        </div>
      </div>
      <div class="productInfo" v-for="(oitem, oindex) in item.cartInfo" :key="oindex">
        <div class="leftBox">
          <div
            class="coverBox"
            @click="jumpTo('/myorder?id=' + item.order_id)"
            style="cursor: pointer"
          >
            <img :src="oitem.productInfo.image" alt="" />
          </div>
          <div class="infoBox">
            <div
              class="name"
              @click="jumpTo('/myorder?id=' + item.order_id)"
              style="cursor: pointer"
            >
              {{
                locale === "zh-cn"
                  ? oitem.productInfo.store_name
                  : oitem.productInfo.en_store_name
              }}
            </div>
            <div class="specificationBox">
              <div class="priceBox">￥{{ oitem.truePrice }}/{{ $t("account.unit") }}</div>
              <div class="num">{{ $t("account.num") }}{{ oitem.cart_num }}</div>
            </div>
            <div class="total">
              {{ $t("account.gong") }}{{ oitem.cart_num }}{{ $t("account.count1")
              }}<span class="totalPrice">￥{{ item.pay_price }}</span
              ><span class="freight">（{{ $t("account.freight") }}0.00）</span>
            </div>
          </div>
        </div>
        <div class="rightBox">
          <div class="status">{{ getOrderStatusName(item) }}</div>
        </div>
      </div>

      <div class="opBox">
        <el-button
          type="primary"
          @click="jumpTo('/payOrder?id=' + item.order_id)"
          v-if="item.status === 0 && item.paid === 0"
          >{{ $t("account.payNow") }}</el-button
        >
        <el-button type="primary" @click="confirmOrder(item)" v-if="item.status === 1"
          >确认收货</el-button
        >
        <el-button
          type="primary"
          v-if="item.status === 2"
          @click="jumpTo('/orderEvaluation?id=' + item.order_id)"
          >立即评价</el-button
        >
        <el-button
          @click="cancelOrder(item.order_id)"
          v-if="item.status === 0 && item.paid === 0"
          >{{ $t("account.cancel") }}</el-button
        >
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.orderList {
  margin-top: 40px;
  min-height: calc(100vh - 600px);
  .item {
    margin-bottom: 30px;
    .topOrderInfo {
      display: flex;
      font-size: 14px;
      color: #666;

      .date {
        margin-right: 50px;
      }
    }

    .productInfo {
      display: flex;
      margin-top: 30px;
      justify-content: space-between;
      border-bottom: 1px solid #f7f7f7;
      padding-bottom: 30px;

      .coverBox {
        width: 130px;
        height: 130px;
        background-color: #fbf7f7;
        border: 1px solid #f5f5f5;
        margin-right: 20px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .leftBox {
        display: flex;

        .name {
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 15px;
          margin-top: 10px;
        }

        .specificationBox {
          display: flex;
          margin-bottom: 30px;
          position: relative;
          left: -2px;

          .priceBox {
            // font-weight: bold;
            color: #000;
          }

          .num {
            margin-left: 60px;
            color: #666;
          }
        }

        .total {
          color: #666;

          .totalPrice {
            font-size: 20px;
            color: #000;
          }

          .freight {
            color: #000;
          }
        }
      }
    }

    .opBox {
      padding: 5px 0;
      // margin-top: 20px;
      display: flex;
      justify-content: end;
      background-color: #fbf7f7;
    }
  }
}
</style>
